package com.android.delivery.util.gson;

import android.content.Context;
import android.content.res.AssetManager;

import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.JsonWriter;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * @author bsnl_yanxuwen
 * @date 2020/3/11 20:18
 * Description :
 * gson转换类型不一样使用
 *   Gson gson = new GsonBuilder()
 *                                             .registerTypeAdapterFactory(TypeAdapters.newFactory(int.class, Integer.class,TypeAdapterUtils.INTEGER))
 *                                             .registerTypeAdapterFactory(TypeAdapters.newFactory(long.class, Long.class, TypeAdapterUtils.LONG))
 *                                             .create();
 */
public class TypeAdapterUtils {
    //int类型的解析器
    public static TypeAdapter<Number> INTEGER = new TypeAdapter<Number>() {
        @Override
        public Number read(JsonReader in) throws IOException {
            if (in.peek() == JsonToken.NULL) {
                in.nextNull();
                return null;
            }
            try {
                return in.nextInt();
            } catch (NumberFormatException e) {
                //这里解析int出错，那么捕获异常并且返回默认值，因为nextInt出错中断了方法，没有完成位移，所以调用nextString()方法完成位移。
                in.nextString();
                return 0;
            }
        }

        @Override
        public void write(JsonWriter out, Number value) throws IOException {
            out.value(value);
        }
    };

    public static TypeAdapter<Number> LONG = new TypeAdapter<Number>() {
        @Override
        public Number read(JsonReader in) throws IOException {
            if (in.peek() == JsonToken.NULL) {
                in.nextNull();
                return null;
            }
            //这里同
            try {
                return in.nextLong();
            } catch (Exception e) {
                in.nextString();
            }
            return 0;
        }

        @Override
        public void write(JsonWriter out, Number value) throws IOException {
            out.value(value);

        }
    };

    public String getJson(Context context, String fileName) {

        StringBuilder stringBuilder = new StringBuilder();
        try {
            AssetManager assetManager = context.getAssets();
            BufferedReader bf = new BufferedReader(new InputStreamReader(
                    assetManager.open(fileName)));
            String line;
            while ((line = bf.readLine()) != null) {
                stringBuilder.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return stringBuilder.toString();
    }
}
